#pragma once

#include <pthread.h>
#include <queue>

const static int g_cap = 5;

template<class T>
class blockqueue
{
public:
    blockqueue(int cap = g_cap)
        : _cap(g_cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_producer, nullptr);
        pthread_cond_init(&_consumer, nullptr);
    }

    void Push(const T input)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())
            pthread_cond_wait(&_producer, &_mutex);
        _q.push(input);
        pthread_cond_signal(&_consumer);
        pthread_mutex_unlock(&_mutex);
    }

    void Pop(T* output)
    {
        pthread_mutex_lock(&_mutex);
        while(isEmpty())
            pthread_cond_wait(&_consumer, &_mutex);
        *output = _q.front();
        _q.pop();
        pthread_cond_signal(&_producer);
        pthread_mutex_unlock(&_mutex);
    }

    ~blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_producer);
        pthread_cond_destroy(&_consumer);
    }

private:
    bool IsFull()
    {
        return _q.size() > _cap;
    }

    bool isEmpty()
    {
        return _q.empty();
    }
private:
    int _cap;
    std::queue<T> _q;
    pthread_mutex_t _mutex;
    pthread_cond_t _producer;
    pthread_cond_t _consumer;
};